package com.mchsdk.paysdk.dialog;

import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.mchsdk.paysdk.bean.VerifyCode;
import com.mchsdk.paysdk.utils.WebViewUtil;
import com.mchsdk.paysdk.callback.PlatformRegisterCallback;
import com.mchsdk.paysdk.callback.RefreshVerifyCode;
import com.mchsdk.paysdk.config.MCHConstant;
import com.mchsdk.paysdk.observer.SecondsWatcher;
import com.mchsdk.paysdk.utils.MCHInflaterUtils;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.StrUtil;
import com.mchsdk.paysdk.utils.ToastUtil;
import com.mchsdk.paysdk.view.util.TimeFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@SuppressLint("NewApi")
public class PlatformRegisterDialog extends DialogFragment implements
        SecondsWatcher, OnClickListener {

    /**
     * 日志打印
     */
    private static final String TAG = "PlatformRegisterDialog";
    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 是否阅读
     */
    boolean isRead=true;
    /**
     * 条款按钮
     */
    Button btnRead;
    /**
     * 返回键监听
     */
    private OnKeyListener mDialogKeyListener;

    /**
     * 注册
     */
    private PlatformRegisterCallback mRegisterCallback;
    /**
     * 快速注册（普通注册）
     */
    private OnClickListener mQuickRegisterClick;

    public void setmQuickRegisterClick(OnClickListener mQuickRegisterClick) {
        this.mQuickRegisterClick = mQuickRegisterClick;
    }

    /**
     * 返回
     */
    private OnClickListener mBackClick;

    /**
     * 失去焦点事件
     */
    private OnFocusChangeListener mFocusChangeListener;
    /**
     * 用户名输入框
     */
    EditText edtAccount;

    /**
     * 密码输入框
     */
    EditText edtPassword;
    /**
     * 短信验证码
     */
    EditText edtMessage;

    Button btnGetPhoneValidateMessage;

//	private VerifyCode verifyCode;

    public PlatformRegisterDialog() {
    }

    @SuppressLint("ValidFragment")
    public PlatformRegisterDialog(Context context) {
        this.mContext = context;
    }

    /**
     * 加载logo的URL
     */
    private String path = MCHConstant.getInstance().getDownloadLogoUrl();
    //下载成功
    private static final int LOAD_SUCCESS = 1;

    //下载失败
    private static final int LOAD_FAIL = -1;

    private ImageView logoImg;

    private HttpURLConnection conn;

    private Bitmap bitmap;
    /**
     * 下载完成后更新UI
     */
    Handler uihandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case LOAD_SUCCESS:

                    if (logoImg != null && bitmap != null) {
                        logoImg.setImageBitmap(bitmap);
                    }
                    MCLog.w(TAG, "下载logo成功");
                    break;

                case LOAD_FAIL:
                    MCLog.w(TAG, "下载logo失败 ");
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View containerView = inflater.inflate(MCHInflaterUtils.getIdByName(mContext,
                "layout", "dialog_mch_platform_register"), container, false);
        //加载logo

        addLogo(containerView);

        edtAccount = (EditText) containerView.findViewById(MCHInflaterUtils
                .getIdByName(mContext, "id", "edt_mc_platform_register_account"));
        edtPassword = (EditText) containerView.findViewById(MCHInflaterUtils
                .getIdByName(mContext, "id", "edt_mc_platform_register_password"));
        edtMessage = (EditText) containerView.findViewById(MCHInflaterUtils
                .getIdByName(mContext, "id", "edt_mc_platform_register_msg"));
        Button btnBackRegister = (Button) (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(mContext, "id",
                        "btn_mc_platform_registertologin"));
        btnBackRegister.setText(StrUtil.addLine(btnBackRegister.getText().toString().trim()));
        btnBackRegister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mBackClick) {
                    TimeFactory.creator(1).getTimeChange()
                            .removeWatcher(PlatformRegisterDialog.this);
                    dismissAllowingStateLoss();
                    mBackClick.onClick(v);
                }
            }
        });
        btnRead = (Button) containerView.findViewById(MCHInflaterUtils
                .getIdByName(mContext, "id", "btn_mc_read"));
        btnRead.setBackgroundResource(MCHInflaterUtils.getIdByName(mContext,
                "drawable", "mch_checkbox_pressed"));
        btnRead.setOnClickListener(readClick);
        containerView.findViewById(MCHInflaterUtils.getIdByName(mContext, "id", "txt_mc_read")).setOnClickListener(readClick);
        containerView.findViewById(MCHInflaterUtils.getIdByName(mContext, "id", "txt_mc_agreement")).setOnClickListener(readClick);
        //---------
        Button btnQuickRegister = (Button) (Button) containerView.findViewById(MCHInflaterUtils.getIdByName(mContext, "id",
                "btn_reg"));
        btnQuickRegister.setText(StrUtil.addLine(btnQuickRegister.getText().toString().trim()));
        btnQuickRegister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mQuickRegisterClick) {
                    dismissAllowingStateLoss();
                    mQuickRegisterClick.onClick(v);
                }

/*				if (null != mBackClick) {
                    TimeUtil.getTimeUtil().getTimeChange()
							.removeWatcher(PlatformRegisterDialog.this);
					dismissAllowingStateLoss();
					mBackClick.onClick(v);
				}
			
*/
            }
        });
        Button btnRegister = (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(mContext, "id",
                        "btn_mc_platform_register"));
        btnRegister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isRead) {
                    ToastUtil.show(mContext, "请阅读并同意用户注册协议");
                    return;
                }
                if (null != mRegisterCallback) {
//					if(null == verifyCode){
//						Toast.makeText(con, "验证码获取失败，请重新获取", 1).show();
//						return;
//					}
                    mRegisterCallback.platformRegister(
                            edtAccount.getText().toString().trim(),
                            edtPassword.getText().toString().trim(),
                            "",//手机注册不需要输入重复密码
                            edtMessage.getText().toString().trim(), "");
                }
            }
        });
        btnGetPhoneValidateMessage = (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(mContext, "id", "msg_mm"));
        btnGetPhoneValidateMessage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                btnGetPhoneValidateMessage.setEnabled(false);
                btnGetPhoneValidateMessage.setBackgroundResource(MCHInflaterUtils.getIdByName(mContext, "drawable", "mc_login_reg_phone_num_disable"));

                if (null != mRegisterCallback) {
                    mRegisterCallback.getPhoneValidateMessage(v, edtAccount.getText().toString().trim(), refreshCode);
                }
            }
        });
        setCancelable(false);

        this.getDialog().setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    TimeFactory.creator(1).getTimeChange()
                            .removeWatcher(PlatformRegisterDialog.this);
                    dismissAllowingStateLoss();
                    if (null != mDialogKeyListener) {
                        mDialogKeyListener.onKey(dialog, keyCode, event);
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });

        return containerView;
    }

    RefreshVerifyCode refreshCode = new RefreshVerifyCode() {

        @Override
        public void showVerifyCode(VerifyCode vc) {
//			verifyCode = vc;
//			if(null != edtMessage){
//				edtMessage.setText(verifyCode.getCode());
//			}
        }
    };
    OnClickListener readClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            isRead = !isRead;
            //点击的是协议连接
            if (MCHInflaterUtils.getIdByName(mContext, "id", "txt_mc_agreement") == v.getId()) {
                isRead = true;
                //显示用户协议
                WebViewUtil.read(mContext, MCHConstant.getInstance().getUserAgreementUrl());
            }
            if (isRead) {
                btnRead.setBackgroundResource(MCHInflaterUtils.getIdByName(mContext,
                        "drawable", "mch_checkbox_pressed"));
            } else {
                btnRead.setBackgroundResource(MCHInflaterUtils.getIdByName(mContext,
                        "drawable", "mch_selectptb_unselected"));
            }
        }
    };

    public void setmDialogKeyListener(OnKeyListener mDialogKeyListener) {
        this.mDialogKeyListener = mDialogKeyListener;
    }

    public void setmRegisterCallback(PlatformRegisterCallback mRegisterCallback) {
        this.mRegisterCallback = mRegisterCallback;
    }

    public void setmBackClick(OnClickListener mBackClick) {
        this.mBackClick = mBackClick;
    }

    public void setmOnFocusChangeListener(OnFocusChangeListener mFocusChangeListener) {
        this.mFocusChangeListener = mFocusChangeListener;
    }

    Handler secondsHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != btnGetPhoneValidateMessage) {
                String seconds = (String) msg.obj;
//				MCLog.e(TAG, "seconds= " + seconds);
                if ("0".equals(seconds)) {
                    btnGetPhoneValidateMessage.setEnabled(true);
                    btnGetPhoneValidateMessage.setText("获取验证码");
                    btnGetPhoneValidateMessage.setBackgroundResource(MCHInflaterUtils.getIdByName(mContext, "drawable", "mc_login_reg_phone_num"));
                } else {
                    btnGetPhoneValidateMessage.setEnabled(false);
                    btnGetPhoneValidateMessage.setText((String) msg.obj);
                    btnGetPhoneValidateMessage.setBackgroundResource(MCHInflaterUtils.getIdByName(mContext, "drawable", "mc_login_reg_phone_num_disable"));
                }
            }
        }

    };

    public void reSendValidateCode() {
        if (null != btnGetPhoneValidateMessage) {
            btnGetPhoneValidateMessage.setEnabled(true);
            btnGetPhoneValidateMessage.setText("获取验证码");
            btnGetPhoneValidateMessage.setBackgroundResource(MCHInflaterUtils.getIdByName(mContext, "drawable", "mc_login_reg_phone_num"));
        }
    }

    @Override
    public void updateSeconds(String seconds) {
        Message msg = new Message();
        msg.what = 0;
        msg.obj = seconds;
        secondsHandler.sendMessage(msg);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置对话框的样式
        setStyle(STYLE_NO_FRAME,
                MCHInflaterUtils.getIdByName(mContext, "style", "MCCustomDialog"));
    }

    @Override
    public void onStart() {
        // 1, 设置对话框的大小
        Window window = getDialog().getWindow();
        WindowManager wm = window.getWindowManager();
        Point windowSize = new Point();
        wm.getDefaultDisplay().getSize(windowSize);
        float size_x = 0;
        float size_y = 0;
        int width = windowSize.x;
        int height = windowSize.y;
        if (width >= height) {// 横屏
            size_x = 0.7f;
            size_y = 0.8f;
            window.getAttributes().width = (int) (windowSize.y * size_y * 1.1);
            window.getAttributes().height = (int) (windowSize.y * size_y);
        } else {// 竖屏
            size_x = 0.9f;
            size_y = 0.855f;
            window.getAttributes().width = (int) (windowSize.x * size_x);
            window.getAttributes().height = (int) (windowSize.x * size_y);
        }
        window.setGravity(Gravity.CENTER);
        super.onStart();
    }

    public static class Builder {
        /**
         * 存放数据的容器
         **/
        private Bundle mmBundle;

        private OnKeyListener mmDialogKeyListener;
        private PlatformRegisterCallback mmRegisterCallback;
        private OnClickListener mmBackdClick;
        private OnClickListener mmPhoneCheckNumber;
        private OnClickListener mmQuickRegisterClick;
        private OnFocusChangeListener mmFocusChangeListener;

        public Builder() {
            mmBundle = new Bundle();
        }

        public Builder setQuickRegisterClick(OnClickListener mmQuickRegisterClick) {
            this.mmQuickRegisterClick = mmQuickRegisterClick;
            return this;
        }


        public Builder setDialogKeyListener(OnKeyListener mmDialogKeyListener) {
            this.mmDialogKeyListener = mmDialogKeyListener;
            return this;
        }

        public Builder setRegisterCallback(
                PlatformRegisterCallback mmRegisterCallback) {
            this.mmRegisterCallback = mmRegisterCallback;
            return this;
        }

        public Builder setBackdClick(OnClickListener mmBackdClick) {
            this.mmBackdClick = mmBackdClick;
            return this;
        }

        public Builder setOnFocusChangeListener(OnFocusChangeListener mmOnFocusChangeListener) {
            this.mmFocusChangeListener = mmOnFocusChangeListener;
            return this;
        }

        public void setPhoneCheckNumber(OnClickListener mmPhoneCheckNumber) {
            this.mmPhoneCheckNumber = mmPhoneCheckNumber;
        }

        private PlatformRegisterDialog create(Context context) {
            final PlatformRegisterDialog dialog = new PlatformRegisterDialog(
                    context);
            // 1,设置显示内容
            dialog.setArguments(mmBundle);
            dialog.setmDialogKeyListener(mmDialogKeyListener);
            dialog.setmRegisterCallback(mmRegisterCallback);
            dialog.setmBackClick(mmBackdClick);
            dialog.setmQuickRegisterClick(mmQuickRegisterClick);
            dialog.setmOnFocusChangeListener(mmFocusChangeListener);
            return dialog;
        }

        public PlatformRegisterDialog show(Context context, FragmentManager fm) {
            if (fm == null) {
                MCLog.e(TAG, "show error : fragment manager is null.");
                return null;
            }
            PlatformRegisterDialog dialog = create(context);
            MCLog.d(TAG, "show SelectPTBTypeDialog.");
            dialog.show(fm, TAG);
            TimeFactory.creator(1).getTimeChange().addWatcher(dialog);
            return dialog;
        }
    }
//	@Override
//	public void show(FragmentManager manager, String tag) {
//		FragmentTransaction ft = manager.beginTransaction();
//		ft.add(this, tag);
//        ft.commitAllowingStateLoss();
//	}

    /**
     * 加载图 logo
     */
    private void addLogo(View view) {

        logoImg = (ImageView) view.findViewById(MCHInflaterUtils
                .getIdByName(mContext, "id", "mch_iv_log"));
        new Thread(new Runnable() {
            @Override
            public void run() {


                getBitmap();
            }


        }).start();
    }

    private void getBitmap() {
        URL url = null;

        InputStream is = null;

        try {
            url = new URL(path);

            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");

            conn.connect();

            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);

                uihandler.sendEmptyMessage(LOAD_SUCCESS);
            }

        } catch (MalformedURLException e) {
            uihandler.sendEmptyMessage(LOAD_FAIL);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

                try {
                    if (is != null) {
                        is.close();
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }

    @Override
    public void onClick(View v) {
    }

}
